import { _decorator, Component, Node, Sprite, director, EditBox, Enum, EventMouse } from 'cc'
import { SunManager } from './manager/SunManager'
import { MouseManager } from './manager/MouseManager'
import { CardState, PlantType } from './Global'
const { ccclass, property } = _decorator

@ccclass('Card')
export class Card extends Component {
  private cardState: CardState = CardState.Coolding // 卡片状态

  @property({ type: Enum(PlantType) })
  public plantType: PlantType
  @property(Node)
  public cardLight: Node = null // 卡片亮着的节点
  @property(Node)
  public cardGray: Node = null // 卡片灰色的节点
  @property(Sprite)
  public cardMask: Sprite = null // 卡片mask
  @property(Number)
  public cdTime: number = 2 // 卡片冷却时间
  private cdTimer: number = 0 // 卡片冷却计时器
  @property(Number)
  private needSunPoint: number = 50 // 需要阳光点数

  start() {
    this.cdTimer = this.cdTime
  }

  update(deltaTime: number) {
    switch (this.cardState) {
      case CardState.Coolding:
        this.CoolingUpdate(deltaTime)
        break
      case CardState.WatingSun:
        this.WatingSunUpdate()
        break
      case CardState.Ready:
        this.ReadyUpdate()
        break
    }
  }

  private CoolingUpdate(dt: number) {
    this.cdTimer -= dt
    this.cardMask.fillRange = -(this.cdTimer / this.cdTime)
    if (this.cdTimer <= 0) {
      // 修改为等阳光的状态
      this.transitionWatingSun()
    }
  }
  transitionWatingSun() {
    // 修改状态,修改激活值
    this.cardState = CardState.WatingSun
    this.cardLight.active = false
    this.cardMask.node.active = false
    this.cardGray.active = true
  }

  private WatingSunUpdate() {
    if (this.needSunPoint <= SunManager.Instance.SunPoint) {
      // 修改为准备状态
      this.transitionReady()
    }
  }

  transitionReady() {
    this.cardState = CardState.Ready
    this.cardGray.active = false
    this.cardMask.node.active = false
    this.cardLight.active = true
  }

  // 准备种植刷新
  private ReadyUpdate() {
    if (this.needSunPoint > SunManager.Instance.SunPoint) {
      // 修改为等待阳光状态
      this.transitionWatingSun()
    }
  }

  // 切换到冷却状态
  transitionCooling() {
    this.cardState = CardState.Coolding
    this.cardGray.active = true
    this.cardMask.node.active = true
    this.cardLight.active = false
    this.cdTimer = this.cdTime
  }

  // 点击事件
  onClick(event:EventMouse) {
    // 判断
    if (this.needSunPoint > SunManager.Instance.SunPoint) {
      return
    }
    if (!MouseManager.Instance.addPlant(this.plantType, event)) {
      return
    }
    // 种植成功以后才进行coolding,并减少太阳值
    SunManager.Instance.subSun(this.needSunPoint)
    this.transitionCooling()
  }
}
